<?php
/**
 * 提供model对象的IOC容器
 *
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/28 0028
 * Time: 17:27
 *
 */
class IocMgr{

    //IOC对象池
   private $_models = Array();
   private static $ci = null;

   //通过配置文件加载注册model
   public function __construct()
   {
       if(empty(self::$ci))
       {
           self::$ci = &get_instance();
       }
       $ioc_json_files = self::$ci->config->item('ioc_load_config_file');
       foreach ($ioc_json_files as $ioc_json_file_path)
       {
           $model_config_str = file_get_contents($ioc_json_file_path);
           $models  =  json_decode($model_config_str,true);
           foreach ($models as $model_name=>$model_path)
           {
               $this->register($model_name,$model_path);
           }
       }

   }

   //获取model
   public function __get($name_key)
   {
       $name_key = strtolower(trim($name_key));
       $model_obj_name = $this->_models[$name_key];
       if(!empty($model_obj_name))
       {
           self::$ci->load->model($model_obj_name);
           return  self::$ci->$model_obj_name;
       }else
       {
           return null;
       }
   }

    //注册model到容器
    private function register($model_name,$model_path="")
    {
       $model_name = strtolower(trim($model_name));
       $model_path = trim($model_path);
       if(empty($model_path))
       {
           $this->_models[$model_name] = $model_name;
       }
       else
       {
           $this->_models[$model_name] = $model_path;
       }
    }

}

//通过IOC容器获取model对象
function IoC()
{
    static $ioc_mgr;
    if(empty($ioc_mgr))
    {
        $ioc_mgr = new IocMgr();
    }
    return $ioc_mgr;
}